<template>
  <div class="login-page">
    <!-- 主容器 -->
    <div class="login-container">
      <!-- 左侧装饰区域 -->
      <div class="login-decoration">
        <div class="decoration-content">
          <div class="logo-area">
            <div class="logo-icon">
              <van-icon name="user-o" size="60" color="#409eff" />
            </div>
            <h1>AI学习助手</h1>
            <p>智能人脸识别登录系统</p>
          </div>

          <div class="feature-list">
            <div class="feature-item">
              <van-icon name="video-o" color="#67c23a" />
              <span>安全人脸识别</span>
            </div>
            <div class="feature-item">
              <van-icon name="chat-o" color="#e6a23c" />
              <span>AI智能对话</span>
            </div>
            <div class="feature-item">
              <van-icon name="description" color="#f56c6c" />
              <span>OCR文字识别</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧登录区域 -->
      <div class="login-form">
        <div class="form-header">
          <h2>欢迎回来</h2>
          <p>请选择登录方式</p>
        </div>

        <!-- 登录方式切换 -->
        <div class="login-tabs">
          <div
            class="tab-item"
            :class="{ active: loginMethod === 'camera' }"
            @click="loginMethod = 'camera'"
          >
            <van-icon name="video-o" />
            <span>摄像头</span>
          </div>
          <div
            class="tab-item"
            :class="{ active: loginMethod === 'upload' }"
            @click="loginMethod = 'upload'"
          >
            <van-icon name="photo-o" />
            <span>上传图片</span>
          </div>
        </div>

        <!-- 摄像头登录 -->
        <div v-if="loginMethod === 'camera'" class="camera-login">
          <div class="camera-area">
            <!-- 摄像头未开启 -->
            <div v-if="!cameraActive && !capturedImage" class="camera-start">
              <div class="camera-placeholder">
                <van-icon name="video-o" size="80" color="#c0c4cc" />
                <p>点击开启摄像头</p>
              </div>
              <van-button
                type="primary"
                size="large"
                @click="startCamera"
                :loading="cameraLoading"
                class="start-camera-btn"
              >
                <van-icon name="video-o" />
                {{ cameraLoading ? '正在开启...' : '开启摄像头' }}
              </van-button>
            </div>

            <!-- 摄像头已开启 -->
            <div v-else-if="cameraActive" class="camera-preview">
              <div class="video-container" id="video-container">
                <div class="face-guide">
                  <div class="face-outline"></div>
                  <p>请将人脸对准中央</p>
                </div>
              </div>
              <div class="camera-controls">
                <van-button type="success" size="large" @click="capturePhoto">
                  <van-icon name="photograph" />
                  拍照
                </van-button>
                <van-button @click="stopCamera">关闭</van-button>
              </div>
            </div>

            <!-- 拍照结果 -->
            <div v-else-if="capturedImage" class="photo-result">
              <div class="photo-preview">
                <img :src="capturedImage" alt="拍摄照片" />
              </div>
              <div class="photo-actions">
                <van-button
                  type="primary"
                  size="large"
                  @click="performLogin"
                  :loading="loginLoading"
                >
                  <van-icon name="success" />
                  {{ loginLoading ? '识别中...' : '确认登录' }}
                </van-button>
                <van-button @click="retakePhoto">重新拍照</van-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 上传图片登录 -->
        <div v-if="loginMethod === 'upload'" class="upload-login">
          <div class="upload-area" @click="selectImage">
            <div v-if="!uploadedImage" class="upload-placeholder">
              <van-icon name="photo-o" size="80" color="#c0c4cc" />
              <p>点击选择图片</p>
              <span class="upload-tip">支持 JPG、PNG、BMP 格式</span>
            </div>
            <div v-else class="uploaded-preview">
              <img :src="uploadedImage" alt="上传的图片" />
              <div class="upload-actions">
                <van-button
                  type="primary"
                  size="large"
                  @click.stop="performLogin"
                  :loading="loginLoading"
                >
                  <van-icon name="success" />
                  {{ loginLoading ? '识别中...' : '确认登录' }}
                </van-button>
                <van-button @click.stop="clearUpload">重新选择</van-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部链接 -->
        <div class="form-footer">
          <p>还没有账号？
            <van-button type="primary" plain size="small" @click="goToRegister">
              立即注册
            </van-button>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { faceLogin } from '@/api/face'
import { setToken, setUserInfo } from '@/utils/auth'

const router = useRouter()

// 状态管理
const loginMethod = ref('camera')
const cameraActive = ref(false)
const cameraLoading = ref(false)
const capturedImage = ref('')
const uploadedImage = ref('')
const loginLoading = ref(false)

// 开启摄像头
const startCamera = async () => {
  cameraLoading.value = true
  try {
    // 检查浏览器支持
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      throw new Error('浏览器不支持摄像头功能')
    }

    console.log('正在请求摄像头权限...')
    const stream = await navigator.mediaDevices.getUserMedia({
      video: {
        width: { ideal: 640, min: 320 },
        height: { ideal: 480, min: 240 },
        facingMode: 'user'
      },
      audio: false
    })

    console.log('摄像头权限获取成功，创建视频元素...')

    // 先更新状态，让DOM显示摄像头预览区域
    cameraActive.value = true

    // 等待Vue DOM更新
    await nextTick()

    // 再等待一小段时间确保DOM完全渲染
    await new Promise(resolve => setTimeout(resolve, 100))

    let container = document.getElementById('video-container')

    // 如果通过ID找不到，尝试通过类名查找
    if (!container) {
      container = document.querySelector('.video-container')
      console.log('通过类名查找到容器:', container)
    }

    // 如果还是找不到，再尝试几次
    let retryCount = 0
    while (!container && retryCount < 5) {
      console.log(`尝试查找视频容器，第 ${retryCount + 1} 次`)
      await new Promise(resolve => setTimeout(resolve, 100))
      container = document.getElementById('video-container') || document.querySelector('.video-container')
      retryCount++
    }

    if (!container) {
      console.error('视频容器未找到，DOM状态:', {
        cameraActive: cameraActive.value,
        byId: !!document.getElementById('video-container'),
        byClass: !!document.querySelector('.video-container'),
        allVideoElements: document.querySelectorAll('[id*="video"], [class*="video"]')
      })
      cameraActive.value = false // 重置状态
      throw new Error('视频容器未找到，请重试')
    }

    console.log('找到视频容器:', container)

    // 清空容器
    container.innerHTML = ''

    // 创建视频元素
    const video = document.createElement('video')
    video.srcObject = stream
    video.autoplay = true
    video.muted = true
    video.playsInline = true // 重要：防止iOS全屏播放
    video.style.width = '100%'
    video.style.height = '100%'
    video.style.objectFit = 'cover'
    video.style.borderRadius = '12px'
    video.style.backgroundColor = '#000'

    // 添加视频事件监听
    video.onloadedmetadata = () => {
      console.log('视频元数据加载完成')
      video.play().catch(e => console.error('视频播放失败:', e))
    }

    video.oncanplay = () => {
      console.log('视频可以播放')
    }

    video.onerror = (e) => {
      console.error('视频播放错误:', e)
    }

    // 添加到容器
    container.appendChild(video)

    // 添加人脸识别指导框
    const guide = document.createElement('div')
    guide.className = 'face-guide-overlay'
    guide.innerHTML = `
      <div class="face-outline"></div>
      <p class="guide-text">请将人脸对准中央区域</p>
    `
    container.appendChild(guide)

    // 保存流引用
    window.currentStream = stream
    window.currentVideo = video

    showToast({ type: 'success', message: '摄像头已开启' })

    console.log('摄像头设置完成')
  } catch (error) {
    console.error('摄像头开启失败:', error)

    let errorMessage = '摄像头开启失败'
    if (error.name === 'NotAllowedError') {
      errorMessage = '请允许访问摄像头权限'
    } else if (error.name === 'NotFoundError') {
      errorMessage = '未找到摄像头设备'
    } else if (error.name === 'NotSupportedError') {
      errorMessage = '浏览器不支持摄像头功能'
    } else if (error.name === 'NotReadableError') {
      errorMessage = '摄像头被其他应用占用'
    } else if (error.message) {
      errorMessage = error.message
    }

    showToast({ type: 'fail', message: errorMessage })
  } finally {
    cameraLoading.value = false
  }
}

// 关闭摄像头
const stopCamera = () => {
  try {
    // 停止视频流
    if (window.currentStream) {
      window.currentStream.getTracks().forEach(track => {
        track.stop()
        console.log('停止视频轨道:', track.kind)
      })
      window.currentStream = null
    }

    // 清理视频元素
    if (window.currentVideo) {
      window.currentVideo.srcObject = null
      window.currentVideo = null
    }

    // 清空容器
    const container = document.getElementById('video-container')
    if (container) {
      container.innerHTML = `
        <div class="face-guide">
          <div class="face-outline"></div>
          <p>请将人脸对准中央</p>
        </div>
      `
    }

    cameraActive.value = false
    showToast({ type: 'success', message: '摄像头已关闭' })
  } catch (error) {
    console.error('关闭摄像头失败:', error)
  }
}

// 拍照
const capturePhoto = () => {
  try {
    const video = window.currentVideo || document.querySelector('#video-container video')
    if (!video) {
      showToast({ type: 'fail', message: '摄像头未开启' })
      return
    }

    // 检查视频是否准备就绪
    if (video.readyState < 2) {
      showToast({ type: 'fail', message: '摄像头还未准备就绪，请稍后再试' })
      return
    }

    console.log('开始拍照，视频尺寸:', video.videoWidth, 'x', video.videoHeight)

    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')

    // 设置画布尺寸
    canvas.width = video.videoWidth || 640
    canvas.height = video.videoHeight || 480

    // 绘制视频帧到画布
    context.drawImage(video, 0, 0, canvas.width, canvas.height)

    // 转换为base64
    const imageData = canvas.toDataURL('image/jpeg', 0.8)

    if (imageData === 'data:,') {
      showToast({ type: 'fail', message: '拍照失败，请重试' })
      return
    }

    capturedImage.value = imageData
    stopCamera()
    showToast({ type: 'success', message: '拍照成功' })

    console.log('拍照完成，图片大小:', imageData.length)
  } catch (error) {
    console.error('拍照失败:', error)
    showToast({ type: 'fail', message: '拍照失败，请重试' })
  }
}

// 重新拍照
const retakePhoto = () => {
  capturedImage.value = ''
  startCamera()
}

// 选择图片
const selectImage = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/jpeg,image/png,image/bmp'
  input.onchange = (e) => {
    const file = e.target.files[0]
    if (file) {
      if (file.size > 10 * 1024 * 1024) {
        showToast({ type: 'fail', message: '图片大小不能超过10MB' })
        return
      }

      const reader = new FileReader()
      reader.onload = (e) => {
        uploadedImage.value = e.target.result
        showToast({ type: 'success', message: '图片上传成功' })
      }
      reader.readAsDataURL(file)
    }
  }
  input.click()
}

// 清除上传
const clearUpload = () => {
  uploadedImage.value = ''
}

// 执行登录
const performLogin = async () => {
  const imageData = capturedImage.value || uploadedImage.value
  if (!imageData) {
    showToast({ type: 'fail', message: '请先获取人脸图片' })
    return
  }

  loginLoading.value = true
  try {
    const response = await faceLogin({ imageData })

    if (response.success || response.code === 200) {
      const userData = response.data || response

      // 保存Token（如果后端没有返回token，生成一个临时token）
      const token = userData.token || `temp_token_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      setToken(token)

      // 使用后端返回的真实用户信息
      const backendUserInfo = response.userInfo || {}

      console.log('🔍 后端返回的用户信息:', backendUserInfo)
      console.log('🔍 完整响应数据:', response)

      const userInfo = {
        id: backendUserInfo.userId || backendUserInfo.id || userData.id || userData.userId || Date.now(),
        userId: backendUserInfo.userId || backendUserInfo.id || userData.id || userData.userId || Date.now(),
        username: backendUserInfo.username || userData.username || userData.name || '用户',
        nickname: backendUserInfo.nickname || backendUserInfo.username || userData.username || '用户',
        email: backendUserInfo.email || userData.email || '',
        phone: backendUserInfo.phonenumber || userData.phonenumber || '',
        sex: backendUserInfo.sex || userData.sex || '',
        avatar: backendUserInfo.avatar || userData.avatar || imageData,
        sessionId: backendUserInfo.sessionId || response.sessionId,
        loginTime: backendUserInfo.loginTime || new Date().toISOString(),
        loginType: backendUserInfo.loginType || 'FACE_RECOGNITION',
        similarity: backendUserInfo.similarity || response.similarity,
        faceAnalysis: backendUserInfo.faceAnalysis || userData
      }

      console.log('✅ 处理后的用户信息:', userInfo)

      setUserInfo(userInfo)

      showToast({ type: 'success', message: '登录成功！' })

      // 使用nextTick确保状态更新后再跳转
      await nextTick()
      await router.push('/')
    } else {
      showToast({ type: 'fail', message: response.message || '人脸识别失败' })
    }
  } catch (error) {
    console.error('登录失败:', error)
    showToast({ type: 'fail', message: '登录失败，请重试' })
  } finally {
    loginLoading.value = false
  }
}

// 跳转注册
const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: 100%;
  max-width: 1000px;
  min-height: 600px;
  display: flex;
}

/* 左侧装饰区域 */
.login-decoration {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 60px 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  position: relative;
  overflow: hidden;
}

.login-decoration::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translate(0, 0) rotate(0deg); }
  50% { transform: translate(-20px, -20px) rotate(180deg); }
}

.decoration-content {
  text-align: center;
  z-index: 1;
  position: relative;
}

.logo-area {
  margin-bottom: 60px;
}

.logo-icon {
  margin-bottom: 20px;
}

.logo-area h1 {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 12px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo-area p {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.feature-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 16px;
  opacity: 0.9;
}

/* 右侧登录区域 */
.login-form {
  flex: 1;
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
}

.form-header {
  text-align: center;
  margin-bottom: 40px;
}

.form-header h2 {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin: 0 0 12px 0;
}

.form-header p {
  color: #606266;
  font-size: 16px;
  margin: 0;
}

/* 登录方式切换 */
.login-tabs {
  display: flex;
  background: #f5f7fa;
  border-radius: 12px;
  padding: 4px;
  margin-bottom: 40px;
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #606266;
  font-weight: 500;
}

.tab-item:hover {
  color: #409eff;
}

.tab-item.active {
  background: white;
  color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

/* 摄像头登录 */
.camera-login {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.camera-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.camera-start {
  text-align: center;
  width: 100%;
}

.camera-placeholder {
  background: #fafbfc;
  border: 2px dashed #e1e6eb;
  border-radius: 16px;
  padding: 60px 20px;
  margin-bottom: 24px;
  transition: all 0.3s ease;
}

.camera-placeholder:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.camera-placeholder p {
  margin: 16px 0 0 0;
  color: #606266;
  font-size: 16px;
}

.start-camera-btn {
  width: 200px;
  height: 48px;
  font-size: 16px;
}

.camera-preview {
  width: 100%;
  text-align: center;
}

.video-container {
  width: 100%;
  height: 300px;
  background: #000;
  border-radius: 16px;
  position: relative;
  overflow: hidden;
  margin-bottom: 20px;
}

.face-guide {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 2;
}

.face-outline {
  width: 180px;
  height: 220px;
  border: 3px solid #409eff;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.7; transform: scale(1.05); }
}

.face-guide p {
  color: white;
  margin-top: 20px;
  font-size: 14px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.face-guide-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
  pointer-events: none;
}

.guide-text {
  color: white;
  font-size: 14px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  margin-top: 20px;
  text-align: center;
}

.camera-controls {
  display: flex;
  gap: 16px;
  justify-content: center;
}

/* 拍照结果 */
.photo-result {
  width: 100%;
  text-align: center;
}

.photo-preview {
  margin-bottom: 20px;
}

.photo-preview img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.photo-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

/* 上传登录 */
.upload-login {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area {
  width: 100%;
  cursor: pointer;
}

.upload-placeholder {
  background: #fafbfc;
  border: 2px dashed #e1e6eb;
  border-radius: 16px;
  padding: 80px 20px;
  text-align: center;
  transition: all 0.3s ease;
}

.upload-placeholder:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-placeholder p {
  margin: 16px 0 8px 0;
  color: #606266;
  font-size: 16px;
}

.upload-tip {
  color: #909399;
  font-size: 14px;
}

.uploaded-preview {
  text-align: center;
}

.uploaded-preview img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.upload-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

/* 底部链接 */
.form-footer {
  text-align: center;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.form-footer p {
  color: #606266;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
    max-width: 500px;
  }

  .login-decoration {
    padding: 40px 20px;
  }

  .login-form {
    padding: 40px 20px;
  }

  .feature-list {
    flex-direction: row;
    justify-content: center;
    flex-wrap: wrap;
  }
}
</style>
